package p10.code;


import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;

public class CellularAutomata {

    private final List<String> mainBoard;
    private final CyclicBarrier barrier;//声明栅栏
    private final Worker[] workers;

    //构造函数
    public CellularAutomata(List<String> board,int count){

        this.mainBoard = board;

        //定义栅栏
        this.barrier = new CyclicBarrier(count,
                () -> {
                    System.out.println("mainBoard size: "+mainBoard.size());
                    mainBoard.clear();
                    System.out.println("清空了mainBoard, 执行下面的步骤");
                    System.out.println("mainBoard size: "+ mainBoard.size());
                    try {
                        Thread.sleep(5000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                });

        this.workers = new Worker[count];
        for(int i=0;i<count;i++){
            workers[i] = new Worker(mainBoard);
        }
    }

    private class Worker implements Runnable {

        private final List<String> board;

        public Worker(List<String> board){
            this.board = board;
        }

        public void run() {
            while(true){
                board.add("1");
                try{
                    Thread.sleep((long) (10000*Math.random()));
                    //如果所有线程没到栅栏，阻塞
                    barrier.await();
                    System.out.println("此次循环执行完毕");
                }catch(InterruptedException | BrokenBarrierException ex){
                    return ;
                }
            }
        }

    }

    public void start() {
        for (Worker worker : workers) new Thread(worker).start();
    }

    public static void main(String[] args) {
        CellularAutomata cellularAutomata = new CellularAutomata(new ArrayList<>(),10);
        cellularAutomata.start();
    }

}
